package com.example.edu.domain.vo;

import lombok.Data;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author yanzhao
 * @date 2022/1/15 18:18
 * @since 1.0.0
 */
@Data
public class PageVO<T> implements Serializable {

    /**
     * 返回数据
     */
    private List<T> data;

    /**
     * 数据总条数
     */
    private long total;

    /**
     * 每页，展示数据条数
     */
    private long pageSize;

    /**
     * 当前页码
     */
    private long current;

    public PageVO() {
    }

    public PageVO(List<T> data, long total) {
        this.data = data;
        this.total = total;
    }

    /**
     * 静态函数，初始化
     */
    public static <T> PageVO<T> getInstance(long pageNum, long pageSize) {
        PageVO<T> pageVO = new PageVO<>();
        pageVO.setCurrent(pageNum);
        pageVO.setPageSize(pageSize);
        return pageVO;
    }

    /**
     * 静态函数，初始化
     */
    public static <T> PageVO<T> getInstance(long pageNum, long pageSize, List<T> dataList, long total) {
        PageVO<T> pageVO = new PageVO<>(dataList, total);
        pageVO.setCurrent(pageNum);
        pageVO.setPageSize(pageSize);
        return pageVO;
    }

    public List<T> getData() {
        return Optional.ofNullable(data).orElse(Collections.emptyList());
    }

    public long getTotal() {
        return Optional.ofNullable(total).orElse(0L);
    }

    /**
     * 兜底返回
     */
    public long getPageSize() {
        return Optional.ofNullable(pageSize).orElse(0L);
    }

    /**
     * 兜底返回
     */
    public long getCurrent() {
        return Optional.ofNullable(current).orElse(0L);
    }

    public long getPages() {
        if (getPageSize() == 0) {
            return 0;
        }
        long pages = getTotal() / getPageSize();
        if (getTotal() % getPageSize() != 0) {
            pages++;
        }
        return pages;
    }

}
